/*
 * Copyright (c) 2023, LXMS (lxinet.cn).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.lxinet.lxms.framework.security.config;

import cn.lxinet.lxms.framework.security.entity.LxmsUser;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt配置
 *
 * @author zcx
 * @date 2023/07/09
 */
@Component
public class JwtConfig {
    public static final String HEADER = "Authorization";
    @Value("${config.jwt.secret}")
    private String secret;
    @Value("${config.jwt.expire}")
    private long expire;
    private static String ISSUER = "https://www.lxinet.cn";

    /**
     * 生成token
     * @param lxmsUser
     * @return
     */
    public String genToken(LxmsUser lxmsUser){
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create().withIssuer(ISSUER).withIssuedAt(new Date()).
                withExpiresAt(new Date((Instant.now().getEpochSecond() + expire) * 1000));
        Map<String, String> claims = new HashMap<>(2);
        claims.put("id", String.valueOf(lxmsUser.getId()));
        claims.put("username", lxmsUser.getUsername());
        claims.put("isAdministrator", String.valueOf(lxmsUser.isAdministrator()));
        claims.forEach((key,value)-> builder.withClaim(key, value));
        return builder.sign(algorithm);
    }
    /**
     * 生成token
     * @param account
     * @return
     */
    public String genToken(String account){
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTCreator.Builder builder = JWT.create().withIssuer(ISSUER).withIssuedAt(new Date()).
                withExpiresAt(new Date((Instant.now().getEpochSecond() + expire) * 1000));
        Map<String, String> claims = new HashMap<>(2);
        claims.put("username", account);
        claims.forEach((key,value)-> builder.withClaim(key, value));
        return builder.sign(algorithm);
    }

    /**
     * 解密jwt
     * @param token
     * @return
     */
    public LxmsUser getUser(String token) {
        try {
            if (null == token){
                return null;
            }
            Algorithm algorithm = Algorithm.HMAC256(secret);;
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            DecodedJWT jwt =  verifier.verify(token);
            Map<String, Claim> map = jwt.getClaims();
            Map<String, String> resultMap = new HashMap<>();
            map.forEach((k,v) -> resultMap.put(k, v.asString()));
            Long id = Long.parseLong(resultMap.get("id"));
            String username = resultMap.get("username");
            Boolean isAdministrator = Boolean.valueOf(resultMap.get("isAdministrator"));
            return new LxmsUser(id, username, isAdministrator);
        }catch (TokenExpiredException e){
            throw e;
        }catch (Exception e){
            return null;
        }
    }

    public LxmsUser getUser(HttpServletRequest request) {
        String token = request.getHeader(HEADER);
        return getUser(token);
    }

}
